/**
 * 预订
 */
Divo.app.BookingForm = function() {
	/* ----------------------- private属性 ----------------------- */
	var win, okBtn, cancelBtn, nav, tn = 1;
	var formPanel, fldName, fldAddress, fldCity, fldZip, fldCountry, fldRate;
	var fldCheckinDate, fldCheckoutDate, fldRoom, fldSmoking, fldNonSmoking;
	var fldCardNumber, fldCardName, fldExpiry;
	var checkinDate, checkoutDate, beds, smoking, card, cardName, expYear, expMonth;
	var cHotel;

	/* ----------------------- private方法 ----------------------- */
	// 创建表单
	function createForm() {
		if (formPanel)
			return;

		// Hotel
		fldName = new Ext.form.TextField( {
			readOnly : true,
			fieldLabel : 'Name',
			tabIndex : tn++,
			id : 'booking-name'
		});
		fldAddress = new Ext.form.TextField( {
			readOnly : true,
			fieldLabel : 'Address',
			tabIndex : tn++,
			id : 'booking-address'
		});
		fldCity = new Ext.form.TextField( {
			readOnly : true,
			fieldLabel : 'City,State',
			tabIndex : tn++,
			id : 'booking-city'
		});
		fldZip = new Ext.form.TextField( {
			readOnly : true,
			fieldLabel : 'Zip',
			tabIndex : tn++,
			id : 'booking-zip'
		});
		fldCountry = new Ext.form.TextField( {
			readOnly : true,
			fieldLabel : 'Country',
			tabIndex : tn++,
			id : 'booking-country'
		});
		fldRate = new Ext.form.TextField( {
			readOnly : true,
			fieldLabel : 'Nightly rate',
			tabIndex : tn++,
			id : 'booking-rate'
		});

		var fsHotel = new Ext.form.FieldSet( {
			title : 'Hotel',
			collapsible : true,
			autoHeight : true,
			items : [fldName, fldAddress, fldCity, fldZip, fldCountry, fldRate]
		});

		// Booking
		fldCheckinDate = new Ext.form.DateField( {
			format : 'Y.m.d',
			fieldLabel : 'Check In Date',
			id : 'booking-checkindate',
			tabIndex : tn++
		});
		fldCheckinDate.on('specialkey', onEnter);
		fldCheckinDate.setValue(new Date());

		fldCheckoutDate = new Ext.form.DateField( {
			format : 'Y.m.d',
			fieldLabel : 'Check Out Date',
			id : 'booking-checkoutdate',
			tabIndex : tn++
		});
		fldCheckoutDate.on('specialkey', onEnter);
		fldCheckoutDate.setValue(new Date());

		var data = [];
		data.push([0, 'One king-size bed']);
		data.push([1, 'Two double beds']);
		data.push([2, 'Three beds']);
		var store = new Ext.data.SimpleStore( {
			fields : ['id', 'name'],
			data : data
		});
		fldRoom = new Ext.form.ComboBox( {
			tabIndex : tn++,
			fieldLabel : 'Room Preference',
			id : 'booking-room',
			store : store,
			displayField : 'name',
			forceSelection : true,
			valueField : 'id',
			typeAhead : false,
			mode : 'local',
			triggerAction : 'all',
			emptyText : '--无--',
			selectOnFocus : true,
			resizable : true,
			editable : true,
			width : 150,
			listWidth : 150
		});
		fldRoom.on('specialkey', onEnter);
		fldRoom.setValue(0);

		fldSmoking = new Ext.form.Radio( {
			boxLabel : 'Smoking',
			fieldLabel : 'Smoking Preference',
			id : 'booking-smoking',
			autoHeight : false,
			height : 20,
			name : 'model',
			checked : false,
			tabIndex : tn++
		});
		fldSmoking.setValue(false);
		fldSmoking.on('specialkey', onEnter);

		fldNonSmoking = new Ext.form.Radio( {
			boxLabel : 'Non Smoking',
			fieldLabel : '',
			labelSeparator : '',
			id : 'booking-nonsmoking',
			autoHeight : false,
			height : 20,
			name : 'model',
			checked : false,
			tabIndex : tn++
		});
		fldNonSmoking.setValue(true);
		fldNonSmoking.on('specialkey', onEnter);

		fldCardNumber = new Ext.form.TextField( {
			fieldLabel : 'Credit Card #',
			tabIndex : tn++,
			id : 'booking-card'
		});
		fldCardNumber.on('specialkey', onEnter);
		fldCardNumber.setValue("1234567890123456");

		fldCardName = new Ext.form.TextField( {
			fieldLabel : 'Credit Card Name',
			tabIndex : tn++,
			id : 'booking-cardname'
		});
		fldCardName.on('specialkey', onEnter);
		fldCardName.setValue("Visa");

		fldExpiry = new Ext.form.DateField( {
			format : 'Y.m',
			fieldLabel : 'Credit Card Expiry',
			id : 'booking-expiry',
			width : 80,
			tabIndex : tn++
		});
		fldExpiry.on('specialkey', onEnter);
		var dd = new Date();
		dd.setYear(dd.getYear()+10);
		fldExpiry.setValue(dd);

		var fsBooking = new Ext.form.FieldSet( {
			title : 'Booking Information',
			collapsible : true,
			autoHeight : true,
			items : [fldCheckinDate, fldCheckoutDate, fldRoom, fldSmoking,
					fldNonSmoking, fldCardNumber, fldCardName, fldExpiry]
		});

		formPanel = new Ext.FormPanel( {
			border : false,
			labelWidth : 200,
			labelPad : 5,
			bodyStyle : 'padding: 2px 5px',
			frame : false,
			items : [fsHotel, fsBooking]
		});
	}

	// 创建窗口
	function createWindow() {
		if (win)
			return;

		win = new Ext.Window( {
			id : 'booking-win',
			title : '',
			// iconCls: 'icon-win',
			autoHeight : true,
			width : 500,
			layout : 'form',
			plain : false,
			buttonAlign : 'right',
			closable : false,
			modal : true,
			items : formPanel
		});

		win.on('show', function() {
			initFocus();
		});

		okBtn = win.addButton( {
			text : '确定',
			tabIndex : tn++
		}, onSubmit, this);

		cancelBtn = win.addButton( {
			text : '取消',
			tabIndex : tn++
		}, onWinHide, this);
	}

	// 初始化表单
	function initForm() {
		win.setTitle('预订');

		fldName.setValue(cHotel.name);
		fldAddress.setValue(cHotel.address);
		fldCity.setValue(cHotel.city + "," + cHotel.state);
		fldZip.setValue(cHotel.zip);
		fldCountry.setValue(cHotel.country);
		fldRate.setValue("$" + cHotel.price);
	}

	function onSubmit() {
		checkinDate = fldCheckinDate.getValue();
		checkoutDate = fldCheckoutDate.getValue();
		beds = fldRoom.getValue();
		smoking = fldSmoking.getValue ? true : false;
		card = fldCardNumber.getValue();
		cardName = fldCardName.getValue();

		if (!validate())
			return;

		expYear = fldExpiry.getValue().getYear();
		expMonth = fldExpiry.getValue().getMonth() + 1;

		Ext.MessageBox.confirm('确认', '要预订吗？', function(btn) {
			if (btn !== 'yes')
				return;

			var onSave = function(retValue) {
				okBtn.enable();
				cancelBtn.enable();

				win.hide();
				Divo.say("预订成功。");
				Divo.publish(Divo.msg.BOOKING_ADD, {
					id : retValue
				});
			}; //TODO: 预订失败处理

			okBtn.disable();
			cancelBtn.disable();

			var hotel = Divo.rmtCreate("hotel", {
				id : cHotel.id
			});

			var bk = {
				hotel : hotel,
				beds : beds,
				checkinDate : checkinDate,
				checkoutDate : checkoutDate,
				creditCard : card,
				creditCardName : cardName,
				creditCardExpiryYear : expYear,
				creditCardExpiryMonth : expMonth,
				smoking : smoking,
				id : 0
			// 这个是必需的
			} // user属性通过服务器端自动注入
			var obj = Divo.rmtCreate("booking", bk);
			Divo.wait("正在保存...");
			Divo.rmtCallAsync("sampleFacade.addBooking", onSave, [obj]);

		});
	}

	// 验证输入数据（TODO: 移到服务器端去验证）
	function validate() {
		if (checkinDate == null || checkinDate.length == 0) {
			fldCheckinDate.markInvalid("必须输入");
			return false;
		}
		if (checkoutDate == null || checkoutDate.length == 0) {
			fldCheckoutDate.markInvalid("必须输入");
			return false;
		}
		if (fldCheckoutDate.getRawValue() < fldCheckinDate.getRawValue()) {
			fldCheckoutDate.markInvalid("必须大于Check in Date");
			return false;
		}
		if (card == null || card.length == 0) {
			fldCardNumber.markInvalid("必须输入");
			return false;
		}
		if (card.length < 16) {
			fldCardNumber.markInvalid("长度必须是16位");
			return false;
		}
		if (cardName == null || cardName.length == 0) {
			fldCardName.markInvalid("必须输入");
			return false;
		}
		if (fldExpiry.getValue() == null || fldExpiry.getValue().length == 0) {
			fldExpiry.markInvalid("必须输入");
			return false;
		}
		return true;
	}

	// 隐藏窗口
	function onWinHide() {
		win.hide();
	}

	// 初始焦点
	function initFocus() {
		var f = Ext.get('booking-checkindate');
		f.focus.defer(100, f);
	}

	// 按回车键导航
	function onEnter(elem, e) {
		if (e.getKey() === e.ENTER) {
			var f = formPanel.form.items.itemAt(this.tabIndex);
			if (f && !f.disabled) {
				f.focus();
			} else {
				okBtn.focus();
			}
			e.stopEvent();
		}
	}

	/* ----------------------- public方法 ----------------------- */
	return {

		/**
		 * 显示对话框
		 * 
		 * @param {Hotel}
		 *            hotel 要预订的酒店
		 */
		showDialog : function(hotel) {
			cHotel = hotel;

			createForm();
			createWindow();
			initForm();
			win.show();

			if (!nav)
				nav = new Ext.KeyNav(win.getEl(), {
					"esc" : onWinHide
				});

		}

	}; // return

}();

// EOP

